<?php
  include 'header.php';
  if ($allow_registration != 1) {
      header('location: index.php');
  }
  if (isset($_GET['activate']))
  {
  if (mysql_real_escape_string($_GET['activate']) == 1 and mysql_real_escape_string($_GET['code']) != "" and $_SESSION['signed_in'] == false) {
      $result = $db->query("SELECT user_id FROM " . $table_prefix . "users WHERE activation_code = '" . mysql_real_escape_string($_GET['code']) . "' ");
      if (mysql_num_rows($result) <= 0) {
          echo "<hr><b>$l_information</b><br/><div align='center'><span style='color:red'>Wrong activation code or code expired.</div></span><br><br>";
          $pageTitle = "Wrong activation code";
          // Get all the page's HTML into a string
          $pageContents = ob_get_contents();
          // Wipe the buffer 
          ob_end_clean();
          echo str_replace('<!--TITLE-->', $pageTitle, $pageContents);
          die;
      } else {
          echo "<hr><b>$l_information</b><br/><div align='center'><span style='color:green'>$l_reg_ok<br></div></span><br><br>";
          $result = $db->query("UPDATE " . $table_prefix . "users SET activation_code = '' WHERE activation_code = '" . mysql_real_escape_string($_GET['code']) . "' ");
          die;
      }
  }
} 
  if (!$_SESSION['signed_in']) {
      $pageTitle = $l_forumname;
      
      if ($_SERVER['REQUEST_METHOD'] != 'POST') {
          /*the form hasn't been posted yet, display it
           note that the action="" will cause the form to post to the same page it is on */
          $tags = array('{USERNAME}', '{PASSWORD}', '{CONFIRM}', '{EMAIL}', '(CAPTCHA)', '{IFCAPTCHA}', '{END}', '{LOGIN}', '(F_PASSWORD)', '{REGISTER}', '{SIGNUP}', '{REGISTRATION}','{MAX_UN}');
          $data = array($l_un, $l_password, $l_confirm_pw, $l_email2, $l_captcha_explain, '', '', $l_login, $l_password2, $l_register, $l_reg_account, $l_registration,$max_username_char);
          
          if ($captcha == 0) {
              $tags = array('{USERNAME}', '{PASSWORD}', '{CONFIRM}', '{EMAIL}', '(CAPTCHA)', '{IFCAPTCHA}', '{END}', '{LOGIN}', '(F_PASSWORD)', '{REGISTER}', '{SIGNUP}', '{REGISTRATION}','{MAX_UN}');
              $data = array($l_un, $l_password, $l_confirm_pw, $l_email2, $l_captcha_explain, '<!--', '-->', $l_login, $l_password2, $l_register, $l_reg_account, $l_registration,$max_username_char);
          }
          if (($ajax_check_username == 0) and ($captcha == 0)) {
              $tags = array('name="user_name" onblur ="validate();"', '{USERNAME}', '{PASSWORD}', '{CONFIRM}', '{EMAIL}', '(CAPTCHA)', '{IFCAPTCHA}', '{END}', '{LOGIN}', '(F_PASSWORD)', '{REGISTER}', '{SIGNUP}', '{REGISTRATION}','{MAX_UN}');
              $data = array('', $l_un, $l_password, $l_confirm_pw, $l_email2, $l_captcha_explain, '<!--', '-->', $l_login, $l_password2, $l_register, $l_reg_account, $l_registration,$max_username_char);
          }
          if (($ajax_check_username == 0) and ($captcha == 1)) {
              $tags = array('onblur ="validate();"', '{USERNAME}', '{PASSWORD}', '{CONFIRM}', '{EMAIL}', '(CAPTCHA)', '{IFCAPTCHA}', '{END}', '{LOGIN}', '(F_PASSWORD)', '{REGISTER}', '{SIGNUP}', '{REGISTRATION}','{MAX_UN}');
              $data = array('', $l_un, $l_password, $l_confirm_pw, $l_email2, $l_captcha_explain, '', '', $l_login, $l_password2, $l_register, $l_reg_account, $l_registration,$max_username_char);
          }
          
          echo str_replace($tags, $data, file_get_contents("./style/" . $default_style . "/registration_form.html"));
      } else {
          $errors = array();
          /* declare the array for later use */
          
          if (isset($_POST['user_name'])) {
              $cu = 'SELECT user_name FROM ' . $table_prefix . 'users WHERE user_name = "' . mysql_real_escape_string($_POST['user_name']) . '"';
              $checkun = $db->query($cu);
              if (mysql_num_rows($checkun) > 0) {
                  $errors[] = $l_error_un_exists;
              }
              //the user name exists
              if (!ctype_alnum($_POST['user_name'])) {
                  $errors[] = $l_error_un_contain;
              }
              if (strlen($_POST['user_name']) > $max_username_char) {
                  $errors[] = $l_error_un_long;
              }
          } else {
              $errors[] = $l_error_un_empty;
          }
               if (strlen($_POST['user_name']) < $min_username_char) {
                  $errors[] = $l_error_un_short;
              }
          if (isset($_POST['user_pass'])) {
              if (strlen($_POST['user_pass']) < $min_password_characters) {
                  $errors[] = $l_error_pw_few;
              }
              
              if ($_POST['user_pass'] != $_POST['user_pass_check']) {
                  $errors[] = $l_error_pw_match;
              }
          } else {
              $errors[] = $l_error_pw_empty;
          }
          if ($_POST['user_email']) {
              $cu = 'SELECT user_email FROM ' . $table_prefix . 'users WHERE user_email = "' . $_POST['user_email'] . '"';
              $checkun = $db->query($cu);
              if (mysql_num_rows($checkun) > 0) {
                  $errors[] = $l_error_used_email;
              }
              
              if (!preg_match("/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i", $_POST['user_email'])) {
                  $errors[] = "$l_error_email_valid";
              }
          } else {
              if (strlen($_POST['user_email']) < 8) {
                  $errors[] = "$l_error_invalid_email";
              }
          }
          if ($captcha == 1) {
              $key = substr($_SESSION['key'], 0, 5);
              $number = $_REQUEST['number'];
              if ($number != $key) {
                  $errors[] = "$l_error_captcha";
              }
          }
          if (!empty($errors)) {
              echo '<hr><b>' . $l_information . '</b><br/><div align="center">' . $l_error_message . '<br /><br /><tr>';
              foreach ($errors as $key => $value) {
                  /* walk through the array so all the errors get displayed */
                  echo '<td><span style="color:red">' . $value . '<br /></td></tr></span>';
              }
              echo '<br /><a href="' . $_SERVER['PHP_SELF'] . '">' . $l_back_to_prev . '</a></div><br /><br />';
          } else {
              //notice the sha1 function which hashes the password
              $sql = "INSERT INTO
          " . $table_prefix . "users(user_name, user_pass, user_email ,user_date, user_level, user_lang)
        VALUES('" . mysql_real_escape_string($_POST['user_name']) . "',
             '" . sha1($_POST['user_pass']) . "',
             '" . mysql_real_escape_string($_POST['user_email']) . "',
            NOW() + INTERVAL $server_time MINUTE + INTERVAL $time_difference HOUR,
            0,'$def_language')";
              
              $result = $db->query($sql) or die(mysql_error());
              if (!$result) {
                  //something went wrong, display the error
                  echo 'Something went wrong while registering. Please try again later.';
                  //echo mysql_error(); //debugging purposes, uncomment when needed
              } else {
                  if ($email_activation == 1) {
                      echo "<hr><b>Activation Required</b><br/><div align='center'>Thank you, <b>$_POST[user_name]</b>, for registering an account.
<br><br>Before you can use your account you must activate it.<br>
An Email containing instructions for activating your account has been sent to $_POST[user_email].
<br>Please follow the instructions.
</div><br />";
                      $url = "http://" . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
                      $confirm_code = md5(uniqid(rand()));
                      $user_id = mysql_insert_id();
                      $email = mysql_real_escape_string($_POST['user_email']);
                      
                      $result5 = $db->query("UPDATE " . $table_prefix . "users set activation_code='$confirm_code' WHERE user_id = " . $user_id . "");
                      
                      $subject = $l_forumname . " | Activate account";
                      $message = "$l_email_message1 " . $_POST[user_name] . ",\r\n\r\n";
                      $message .= "Thank you for registering an account at $l_forumname \r\n\r\n";
                      $message .= "Click on the link below to activate your account: \r\n";
                      $message .= "" . $url . "?activate=1&code=$confirm_code\r\n\r\nRegards, \r\n" . $l_forumname . " Team.";
                      
                      if ($smtp == "local") {
                          $myemail = $smtp_username;
                          //mysql_real_escape_string($_POST['user_email']);    //"$_POST[user_email]";
                          $to = mysql_real_escape_string($_POST['user_email']);
                          $subject = $subject;
                          $sendmessage = $message;
                          $headers = "From: $l_forumname<$myemail>" . "\r\n" . "Reply-To: $myemail" . "\r\n" . 'X-Mailer: PHP/' . phpversion();
                          $sentmail = mail($to, $subject, $sendmessage, $headers);
                      }
                      //END LOCAL mail
                      //SMTP MAIL
                      if ($smtp == "smtp") {
                          error_reporting(E_STRICT);
                          date_default_timezone_set('America/Toronto');
                          require_once('./phpmailer/class.phpmailer.php');
                          $mail = new PHPMailer();
                          
                          $body = "$l_email_message1 " . $_POST[user_name] . ",\r\n<br /><br />
Thank you for registering an account at $l_forumname <br /><br />
Click on the link below to activate your account: \r\n<br /><br />
" . $url . "?activate=1&code=$confirm_code <br /><br />Regards, \r\n" . $l_forumname . " Team.";
                          $body = eregi_replace("[\]", '', $body);
                          
                          // telling the class to use SMTP
                          $mail->IsSMTP();
                          // SMTP server
                          $mail->Host = $smtp_server;
                          // enables SMTP debug information (for testing)
                          $mail->SMTPDebug = 1;
                          // 1 = errors and messages, 2 = messages only
                          // enable SMTP authentication
                          $mail->SMTPAuth = true;
                          // sets the SMTP server
                          $mail->Host = $smtp_server;
                          $mail->SMTPSecure = $smtp_secure;
                          // set the SMTP port for the GMAIL server
                          $mail->Port = $smtp_port;
                          // SMTP account username
                          $mail->Username = $smtp_username;
                          // SMTP account password
                          $mail->Password = $smtp_password;
                          
                          $mail->SetFrom($smtp_username, $l_forumname);
                          $mail->AddReplyTo($smtp_username, $l_forumname);
                          $mail->Subject = $l_forumname . " | Activate account";
                          // optional, comment out and test
                          $mail->AltBody = "$l_email_alt_body";
                          
                          $mail->MsgHTML($body);
                          $address = mysql_real_escape_string($_POST['user_email']);
                          $mail->AddAddress($address, "Ivan A.");
                          
                          if (!$mail->Send()) {
                              echo "Mailer Error: " . $mail->ErrorInfo;
                          }
                      }
                      //END SMTP MAIL
                      
                  }
                  echo "<hr><b>$l_information</b><br/><div align='center'>$l_reg_ok</div><br />";
              }
          }
      }
  } else {
      echo "<hr><br><b>$l_information<b><br /><div align='center'><span style='color:red'>$l_already_logged</span></div><br />";
  }
  // Get all the page's HTML into a string
  $pageContents = ob_get_contents();
  // Wipe the buffer 
  ob_end_clean();
  echo str_replace('<!--TITLE-->', $pageTitle, $pageContents);
?>